<template>
  <div class="product-upload-modal">
    <div class="modal-backdrop" @click="closeModal"></div>
    <div class="product-upload-container" @click.stop>
      <div class="modal-header">
        <h2>上传商品</h2>
        <div class="close-button" @click="$emit('close')">X</div>
      </div>
      
      <form @submit.prevent="uploadProduct" class="upload-form">
        <div class="form-group">
          <label for="product-title">商品名称:</label>
          <input 
            type="text" 
            id="product-title" 
            v-model="productForm.title" 
            placeholder="请输入商品名称"
            required
          >
          <span v-if="validationErrors.title" class="error-text">{{ validationErrors.title }}</span>
        </div>
        
        <div class="form-group">
          <label for="product-price">价格:</label>
          <input 
            type="number" 
            id="product-price" 
            v-model="productForm.price" 
            placeholder="请输入商品价格"
            step="0.01"
            min="0"
            required
          >
          <span v-if="validationErrors.price" class="error-text">{{ validationErrors.price }}</span>
        </div>
        
        <div class="form-group">
          <label for="product-desc">商品描述:</label>
          <textarea 
            id="product-desc" 
            v-model="productForm.desc" 
            placeholder="请输入商品描述"
            rows="4"
          ></textarea>
          <span v-if="validationErrors.desc" class="error-text">{{ validationErrors.desc }}</span>
        </div>
        
        <div class="form-group">
          <label for="product-image">商品图片:</label>
          <div 
            class="file-upload-container"
            @dragover.prevent="dragover = true"
            @dragleave.prevent="dragover = false"
            @drop.prevent="handleFileDrop"
            :class="{ 'active-dropzone': dragover }"
          >
            <div class="file-upload-prompt">
              <i class="upload-icon">📁</i>
              <p>拖放图片到此处上传</p>
              <button class="upload-button" @click="triggerFileInput">选择图片</button>
              <input 
                type="file" 
                id="product-image" 
                @change="handleImageUpload"
                accept="image/*"
                class="hidden-input"
                ref="fileInput"
              >
            </div>
          </div>
          <div class="upload-progress" v-if="uploading">
            <div class="progress-bar">
              <div class="progress-bar-inner"></div>
            </div>
            <span class="progress-text">上传中...</span>
          </div>
          <div class="image-preview-container" v-if="imagePreview">
            <div class="image-preview">
              <img :src="imagePreview" alt="商品预览图" />
              <div class="upload-success" v-if="productForm.picPaths && !uploading">
                <i class="success-icon">✓</i>
              </div>
              <div class="loading-overlay" v-if="uploading">
                <div class="loading-spinner"></div>
              </div>
            </div>
          </div>
          <span v-if="validationErrors.picPaths" class="error-text">{{ validationErrors.picPaths }}</span>
        </div>
        
        <div class="error-message" v-if="uploadError">{{ uploadError }}</div>
        
        <div class="button-group">
          <button type="button" class="cancel-button" @click="$emit('close')">取消</button>
          <button type="submit" class="submit-button" :disabled="uploading">
            {{ uploading ? '上传中...' : '提交' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ProductUpload',
  data() {
    return {
      showModal: true,
      productForm: {
        title: '',
        price: '',
        desc: '',
        picPaths: '',
        userid: ''
      },
      validationErrors: {
        title: '',
        price: '',
        desc: '',
        picPaths: ''
      },
      uploading: false,
      uploadError: '',
      imagePreview: null,
      imageFile: null,
      existingProducts: [],
      dragover: false
    };
  },
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  methods: {
    closeModal() {
      this.showModal = false;
      this.$emit('close');
    },
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    async fetchExistingProducts() {
      try {
        const response = await fetch('/api/demo/getallitems?typeIndex=2');
        if (!response.ok) {
          console.error('获取商品列表失败');
          return;
        }

        const data = await response.json();
        this.existingProducts = data || [];
      } catch (error) {
        console.error('获取商品列表错误:', error);
      }
    },
    validateForm() {
      let isValid = true;
      this.validationErrors = {
        title: '',
        price: '',
        desc: '',
        picPaths: ''
      };
      
      if (!this.productForm.title.trim()) {
        this.validationErrors.title = '商品名称不能为空';
        isValid = false;
      }
      else {
        // 检查商品名称是否重复
        const titleExists = this.existingProducts.some(product => 
          product.title.toLowerCase() === this.productForm.title.trim().toLowerCase()
        );

        if (titleExists) {
          this.validationErrors.title = '该商品名称已存在，请使用其他名称';
          isValid = false;
        }
      }
      
      if (!this.productForm.price) {
        this.validationErrors.price = '商品价格不能为空';
        isValid = false;
      } else if (isNaN(this.productForm.price) || parseFloat(this.productForm.price) < 0) {
        this.validationErrors.price = '请输入有效的价格';
        isValid = false;
      }
      

      

      
      return isValid;
    },
    
    async handleImageUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      this.processUploadFile(file);
    },
    
    handleFileDrop(event) {
      this.dragover = false;
      const file = event.dataTransfer.files[0];
      if (!file || !file.type.startsWith('image/')) {
        this.uploadError = '请上传有效的图片文件';
        return;
      }
      
      this.processUploadFile(file);
    },
    
    async processUploadFile(file) {
      this.imageFile = file;
      
      // 创建预览
      const reader = new FileReader();
      reader.onload = (e) => {
        this.imagePreview = e.target.result;
      };
      reader.readAsDataURL(file);
      
      // 立即上传图片
      this.uploading = true;
      this.uploadError = '';
      
      try {
        const formData = new FormData();
        formData.append('wangeditor-uploaded-image', file);
        
        const imageResponse = await fetch('/api/demo/image', {
          method: 'POST',
          body: formData
        });
        
        if (!imageResponse.ok) {
          throw new Error('图片上传失败');
        }
        
        const imageData = await imageResponse.json();
        
        if (imageData.errno !== 0) {
          throw new Error(imageData.message || '图片上传失败');
        }
        
        // 保存图片URL
        this.productForm.picPaths = imageData.data.url;
      } catch (error) {
        console.error('图片上传错误:', error);
        this.uploadError = error.message || '图片上传失败，请重试';
      } finally {
        this.uploading = false;
      }
    },
    
    async uploadProduct() {
      // 重新获取最新的商品列表以确保查重的准确性
      await this.fetchExistingProducts();
      
      // 表单验证
      if (!this.validateForm()) {
        return;
      }
      
      this.uploading = true;
      this.uploadError = '';
      
      try {
        // 直接使用已上传的图片URL
        // 提交商品信息
        const productData = {
          typeIndex: 2, // 商品类型索引
          title: this.productForm.title,
          price: parseFloat(this.productForm.price),
          desc: this.productForm.desc,
          picPaths: this.productForm.picPaths,
          userid: this.userId
        };
        
        const productResponse = await fetch('/api/demo/additem', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(productData)
        });
        
        if (!productResponse.ok) {
          throw new Error('商品信息提交失败');
        }
        
        const productResult = await productResponse.json();
        
        // 提交成功
        this.$emit('uploaded', {
          ...productData,
          id: productResult.id
        });
        
        // 重置表单
        this.resetForm();
        
      } catch (error) {
        console.error('上传商品错误:', error);
        this.uploadError = error.message || '上传失败，请重试';
      } finally {
        this.uploading = false;
      }
    },
    
    resetForm() {
      this.productForm = {
        title: '',
        price: '',
        desc: '',
        picPaths: '',
        userid: this.userId
      };
      this.imagePreview = null;
      this.imageFile = null;
      this.uploadError = '';
      this.validationErrors = {
        title: '',
        price: '',
        desc: '',
        picPaths: ''
      };
    }
  },
  created() {
    // 设置用户ID
    this.productForm.userid = this.userId;
    this.fetchExistingProducts();
  }
};
</script>

<style scoped>
.product-upload-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

.modal-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(5px);
  cursor: pointer;
}

.product-upload-container {
  background-color: #fff;
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4);
  z-index: 1002;
  padding: 0 0 25px 0;
}

.modal-header {
  background-color: #f8f8f8;
  padding: 20px 25px;
  border-radius: 16px 16px 0 0;
  border-bottom: 1px solid #eaeaea;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.modal-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.5rem;
  font-weight: 600;
}

.upload-form {
  padding: 0 25px;
}
.close-button {
  position: absolute;
  top: 50%;
  right: 15px;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  transition: color 0.2s;
  transform: translateY(-50%);
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.close-button:hover {
  color: #000;
  background-color: rgba(0, 0, 0, 0.05);
}

.upload-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}

.form-group label {
  margin-bottom: 5px;
  font-weight: 600;
  color: #555;
}

.form-group input,
.form-group textarea {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #4a90e2;
  outline: none;
}

.error-text {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
}

.error-message {
  background-color: #fdecea;
  color: #e74c3c;
  padding: 10px;
  border-radius: 5px;
  margin: 10px 0;
  text-align: center;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.cancel-button,
.submit-button {
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.2s;
  border: none;
}

.cancel-button {
  background-color: #f1f1f1;
  color: #666;
}

.cancel-button:hover {
  background-color: #e1e1e1;
}

.submit-button {
  background-color: #4CAF50;
  color: white;
}

.submit-button:hover {
  background-color: #45a049;
}

.submit-button:disabled {
  background-color: #a0d8a3;
  cursor: not-allowed;
}

.image-preview {
  margin-top: 10px;
  text-align: center;
  max-height: 200px;
  overflow: hidden;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.image-preview img {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
}
/* 新的文件上传样式 */
.file-upload-container {
  border: 2px dashed #ddd;
  padding: 30px;
  text-align: center;
  border-radius: 8px;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: all 0.3s;
}

.file-upload-container:hover {
  border-color: #4CAF50;
  background-color: #f5f9f5;
}

.active-dropzone {
  border-color: #4CAF50;
  background-color: #edf7ee;
}

.file-upload-prompt {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-icon {
  font-size: 36px;
  margin-bottom: 10px;
  color: #999;
}

.file-upload-container:hover .upload-icon {
  color: #4CAF50;
}

.file-upload-prompt p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.hidden-input {
  position: absolute;
  width: 1px;
  height: 1px;
  opacity: 0;
  pointer-events: none;
}

.upload-progress {
  margin-top: 15px;
}

.progress-bar {
  height: 6px;
  background-color: #eee;
  border-radius: 3px;
  margin-bottom: 5px;
  overflow: hidden;
}

.progress-bar-inner {
  height: 100%;
  width: 100%;
  background-color: #4CAF50;
  animation: progress-animation 1.5s infinite ease-in-out;
  transform-origin: left center;
}

.progress-text {
  font-size: 12px;
  color: #666;
}

.image-preview-container {
  margin-top: 15px;
  position: relative;
}

.image-preview {
  margin-top: 10px;
  text-align: center;
  max-height: 200px;
  overflow: hidden;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  position: relative;
}

.upload-success {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #4CAF50;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.success-icon {
  font-size: 14px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(76, 175, 80, 0.2);
  border-left-color: #4CAF50;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes progress-animation {
  0% {
    transform: scaleX(0);
  }
  50% {
    transform: scaleX(1);
  }
  100% {
    transform: scaleX(0);
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.upload-button {
  margin-top: 15px;
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.upload-button:hover {
  background-color: #45a049;
}
</style>